package com.demo.goods.web;

import com.demo.goods.config.PatternProperties;
import com.demo.goods.pojo.Goods;
import com.demo.goods.service.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/goods")
@RefreshScope
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private PatternProperties patternProperties;

    @GetMapping("/{id}")
    public Goods getInfo(@PathVariable("id") Long id) {
        System.out.println(patternProperties.getPageSize());
        return goodsService.getById(id);
    }

    @GetMapping("/list")
    public List<Goods> list() {
        return goodsService.list().stream().limit(Long.valueOf(patternProperties.getPageSize())).collect(Collectors.toList());
    }

    @PostMapping("/add")
    public Map<String, Object> add(@RequestBody Goods goods) {
        Map<String, Object> response = new HashMap<>();
        if (goodsService.save(goods)) {
            response.put("code", 200);
            response.put("msg", "添加成功");
        } else {
            response.put("code", 500);
            response.put("msg", "添加失败");
        }
        return response;
    }

    @PutMapping("/update")
    public Map<String, Object> edit(@RequestBody Goods goods) {
        Map<String, Object> response = new HashMap<>();
        if (goodsService.updateById(goods)) {
            response.put("code", 200);
            response.put("msg", "修改成功");
        } else {
            response.put("code", 500);
            response.put("msg", "修改失败");
        }
        return response;
    }


    @DeleteMapping("/{id}")
    public Map<String, Object>  remove(@PathVariable("id") Long id) {
        Map<String, Object> response = new HashMap<>();
        if (goodsService.removeById(id)) {
            response.put("code", 200);
            response.put("msg", "删除成功");
        } else {
            response.put("code", 500);
            response.put("msg", "删除失败");
        }
        return response;
    }
}
